package com.poem.springboot_rear.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.poem.springboot_rear.common.LogAs;
import com.poem.springboot_rear.common.LogType;
import com.poem.springboot_rear.common.Result;
import com.poem.springboot_rear.entity.Activity;
import com.poem.springboot_rear.entity.User;
import com.poem.springboot_rear.service.ActivityService;
import com.poem.springboot_rear.service.UserService;
import com.poem.springboot_rear.utils.TokenUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.swing.plaf.SpinnerUI;
import java.util.List;

/**
 * 功能：
 * 作者： 小祝小祝
 * 日期： 2023/11/20 19:28
 */
@CrossOrigin
@RestController
@RequestMapping("/activity")
public class ActivityController {

    @Resource
    ActivityService activityService;
    @Resource
    UserService userService;

    /**
     * 新增活动
     *
     * @param activity
     * @return
     */
    @LogAs(operation = "新增活动", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Activity activity) {
        User currentUser = TokenUtils.getCurrentUser(); // 获取当前登录的用户信息
        activity.setUserid(currentUser.getId()); // 获取登录信息里的用户id
        try {
            activityService.save(activity);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("添加数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 修改活动
     *
     * @param activity
     * @return
     */
    @LogAs(operation = "修改活动", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Activity activity) {
        try {
            activityService.updateById(activity);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("添加数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 单个删除活动
     *
     * @param id
     * @return
     */
    @LogAs(operation = "删除活动（单个）", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        activityService.removeById(id);
        return Result.success(id);
    }

    /**
     * 批量删除活动
     *
     * @param ids
     * @return
     */
    @LogAs(operation = "批量删除活动", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        activityService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 查找单个
     *
     * @param id
     * @return
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Activity byId = activityService.getById(id);
        return Result.success(byId);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageIndex,
                               @RequestParam Integer pageSize,
                               @RequestParam String title) {
        // 创建条件构造器
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<Activity>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(title),"title",title);
//        queryWrapper.eq("status",1); // 筛选条件，status为1的
        Page<Activity> page = activityService.page(new Page<>(pageIndex, pageSize), queryWrapper);
        List<Activity> records = page.getRecords();
        // 通过for循环list，从每行中拿出id，然后根据id去查询user表
        for (Activity record : records){
            Integer authorId = record.getUserid();
            User user = userService.getById(authorId);
            if (user != null) {
                record.setAuthor(user.getName());
            }
        }
        return Result.success(page);
    }
}
